'use strict';
var util = require('util');
var yeoman = require('yeoman-generator');
var fs = require('fs');

var Generator = module.exports = function Generator(args, options){
    yeoman.generators.Base.apply(this, arguments);
    var utils_path = this.templatePath('../../../utils.js');
    this.utils = require(utils_path);
};
util.inherits(Generator, yeoman.generators.Base);

Generator.prototype.askFor = function askFor(){
    var prompts = [{
        type: 'input',
        name: 'uri',
        message: '请输入路由的URL',
        default: '/home'
    },{
        type: 'input',
        name: 'controller',
        message: '请输入与路由关联的控制器名',
        default: 'HomeCtrl'
    }, {
        type: 'input',
        name: 'view',
        message: '请输入路由关联的视图',
        default: 'home.html'
    }];
    var cb = this.async();
    this.prompt(prompts, function(answer){
        this.controller = answer.controller;
        this.uri = answer.uri;
        this.view = answer.view;
        cb();
    }.bind(this));
};

Generator.prototype.projectfiles = function projectfiles(){
    //1. 如果控制器不存在,那么创建控制器
    if(! fs.existsSync('js/controllers/'+this.controller+'.js')){
        this.log(util.format('控制器: %s 不存在,开始创建', this.controller));
        this.utils.addController(this, this.controller)
    }
    //2. 如果视图不存在,那么创建视图
    if(! fs.existsSync(util.format('js/views/%s', this.view))){
        this.log(util.format('视图文件: %s 不存在,开始创建', this.view));
        this.utils.addView(this, this.view);
    }
    //3. 开始写入到route.js中
    var content = this.readFileAsString('js/route.js');
    var new_route = util.format('when("%s",{templateUrl: "/js/views/%s",controller:"%s"}).otherwise', this.uri, this.view, this.controller);
    fs.writeFileSync('js/route.js', content.replace('otherwise', new_route));
};